package com.nc.delivery_project.client.users;

import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.Place;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.google.web.bindery.requestfactory.shared.Receiver;
import com.google.web.bindery.requestfactory.shared.ServerFailure;
import com.nc.delivery_project.client.ClientFactory;
import com.nc.delivery_project.client.request.UserRequest;
import com.nc.delivery_project.client.user_details.UserDetailsPlace;
import com.nc.delivery_project.shared.proxy.UserProxy;

import java.util.List;

/**
 * Created by miroshnik on 12/28/2014.
 */
public class UsersActivity extends AbstractActivity implements UsersPresenter{

    private UsersView view;
    private ClientFactory clientFactory;

    public UsersActivity(UsersPlace place, ClientFactory clientFactory) {
        this.clientFactory = clientFactory;
    }

    @Override
    public void start(AcceptsOneWidget panel, EventBus eventBus) {
        if (view == null) {
            view = new UsersView();
        }

        view.setPresenter(this);
        panel.setWidget(view.asWidget());
        view.start();
        
        loadUsers();
    }

    @Override
    public void goTo(Place place) {
        clientFactory.getPlaceController().goTo(place);
    }

    @Override
    public ClientFactory getClientFactory() {
        return clientFactory;
    }

    @Override
    public void loadUsers() {
        final UserRequest userRequest = clientFactory.getRequestFactory().createUserRequest();

        userRequest.read().with("role").fire(new Receiver<List<UserProxy>>() {
            @Override
            public void onSuccess(List<UserProxy> response) {
                GWT.log("success");
                GWT.log(response.get(0).getRole().getTitle());
                view.setDataList(response);
            }

            @Override
            public void onFailure(ServerFailure error) {
                super.onFailure(error);
                GWT.log(error.toString());
            }
        });
    }
}
